package wangyiyun.baseLexe.first;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestThreadMax {
    static Map<Integer,User>  map = new HashMap<>();
    //4个人 * 5
    private static final int len_thread = 20;
    static ExecutorService executor = Executors.newFixedThreadPool(len_thread);
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(len_thread);
        long start = System.currentTimeMillis();
        for (int i=0;i<len_thread;i++){
            User _lock = map.computeIfAbsent(i%4,k->new User("user"+(k%4)));
            executor.submit(new SubClass(_lock,latch));
        }
        latch.await();
        System.out.println(Thread.currentThread().getName() + " has finished. Spend Time = " + (System.currentTimeMillis() - start));
    }
}

class SubClass implements Runnable{

    private User user;
    private CountDownLatch latch;

    public SubClass(User user, CountDownLatch latch) {
        this.user = user;
        this.latch = latch;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "--" + user.toString());
        synchronized (user){
            try {
                Thread.sleep(1000);
                System.out.println(user.getUser());
                latch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class User{
    private String user;

    public User(String user) {
        this.user = user;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }
}